# Oh My Posh 本地构建和打包脚本
# 用于从fork的仓库构建并创建winget包

param(
    [Parameter(Mandatory = $false)]
    [string]$Version = "dev-$(Get-Date -Format 'yyyyMMdd-HHmm')",
    
    [Parameter(Mandatory = $false)]
    [ValidateSet('x64', 'arm64', 'x86')]
    [string]$Architecture = 'x64',
    
    [Parameter(Mandatory = $false)]
    [switch]$BuildMSI,
    
    [Parameter(Mandatory = $false)]
    [switch]$CreateWingetPackage,
    
    [Parameter(Mandatory = $false)]
    [switch]$InstallLocal
)

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true

Write-Host "=== Oh My Posh 本地构建脚本 ===" -ForegroundColor Green
Write-Host "版本: $Version" -ForegroundColor Yellow
Write-Host "架构: $Architecture" -ForegroundColor Yellow

# 设置Go代理为中国镜像
$env:GOPROXY = "https://goproxy.cn,direct"
Write-Host "已设置Go代理: $env:GOPROXY" -ForegroundColor Cyan

# 步骤1: 构建oh-my-posh可执行文件
Write-Host "`n步骤1: 构建oh-my-posh可执行文件..." -ForegroundColor Blue

Push-Location "src"
try {
    Write-Host "清理旧的构建..."
    if (Test-Path "oh-my-posh.exe") {
        Remove-Item "oh-my-posh.exe" -Force
    }
    
    # 设置构建标志
    $buildDate = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
    $ldflags = "-s -w -X 'github.com/jandedobbeleer/oh-my-posh/src/build.Version=$Version' -X 'github.com/jandedobbeleer/oh-my-posh/src/build.Date=$buildDate'"
    
    Write-Host "构建命令: go build -v -ldflags `"$ldflags`" -o oh-my-posh.exe"
    go build -v -ldflags $ldflags -o oh-my-posh.exe
    
    if (Test-Path "oh-my-posh.exe") {
        Write-Host "✓ 构建成功!" -ForegroundColor Green
        
        # 测试版本
        $versionOutput = & ".\oh-my-posh.exe" version 2>&1
        Write-Host "版本信息: $versionOutput" -ForegroundColor Cyan
    } else {
        throw "构建失败: 未找到oh-my-posh.exe"
    }
} finally {
    Pop-Location
}

# 步骤2: 创建分发目录并复制文件
Write-Host "`n步骤2: 准备分发文件..." -ForegroundColor Blue

$distDir = "dist"
if (!(Test-Path $distDir)) {
    New-Item -Path $distDir -ItemType Directory | Out-Null
}

# 根据架构设置文件名
switch ($Architecture) {
    'x86' { $distFileName = "posh-windows-386.exe" }
    'x64' { $distFileName = "posh-windows-amd64.exe" }
    Default { $distFileName = "posh-windows-$Architecture.exe" }
}

Copy-Item "src\oh-my-posh.exe" "$distDir\$distFileName" -Force
Copy-Item "src\oh-my-posh.exe" "$distDir\oh-my-posh.exe" -Force
Write-Host "✓ 文件复制到 $distDir\" -ForegroundColor Green

# 步骤3: 构建MSI包 (可选)
if ($BuildMSI) {
    Write-Host "`n步骤3: 构建MSI安装包..." -ForegroundColor Blue
    
    # 检查WiX工具是否可用
    try {
        wix --version | Out-Null
        Write-Host "✓ 找到WiX工具" -ForegroundColor Green
    } catch {
        Write-Warning "未找到WiX工具，跳过MSI构建。请安装WiX v4工具集。"
        Write-Host "安装命令: winget install WiX.Toolset" -ForegroundColor Yellow
        return
    }
    
    Push-Location "packages\msi"
    try {
        # 创建输出目录
        if (!(Test-Path "out")) {
            New-Item -Path "out" -ItemType Directory | Out-Null
        }
        if (!(Test-Path "dist")) {
            New-Item -Path "dist" -ItemType Directory | Out-Null
        }
        
        # 复制可执行文件
        Copy-Item "..\..\dist\$distFileName" "dist\oh-my-posh.exe" -Force
        
        # 设置环境变量
        $env:VERSION = $Version
        
        # 构建MSI
        $fileName = "install-$Architecture.msi"
        $installer = "$PWD\out\$fileName" -replace '\\', '/'
        
        Write-Host "构建MSI: $fileName"
        wix build -arch $Architecture -out $installer .\oh-my-posh.wxs
        
        if (Test-Path "out\$fileName") {
            Write-Host "✓ MSI构建成功: packages\msi\out\$fileName" -ForegroundColor Green
        } else {
            Write-Warning "MSI构建失败"
        }
    } finally {
        Pop-Location
    }
}

# 步骤4: 创建本地winget包 (可选)
if ($CreateWingetPackage) {
    Write-Host "`n步骤4: 创建本地Winget包..." -ForegroundColor Blue
    
    $wingetDir = "winget-local"
    if (Test-Path $wingetDir) {
        Remove-Item $wingetDir -Recurse -Force
    }
    New-Item -Path $wingetDir -ItemType Directory | Out-Null
    
    # 创建本地版本的winget清单文件
    $packageId = "Xuan_er123.OhMyPosh"
    $publisherName = "Xuan_er123"
    
    # 主清单文件
    $mainManifest = @"
PackageIdentifier: $packageId
PackageVersion: $Version
DefaultLocale: en-US
ManifestType: version
ManifestVersion: 1.6.0
"@
    
    # 安装程序清单
    $installerManifest = @"
PackageIdentifier: $packageId
PackageVersion: $Version
ReleaseDate: $(Get-Date -Format "yyyy-MM-dd")
Platform:
- Windows.Desktop
MinimumOSVersion: 10.0.0.0
InstallerType: portable
Installers:
- Architecture: $Architecture
  InstallerUrl: file:///$((Resolve-Path "$distDir\oh-my-posh.exe").Path -replace '\\', '/')
  InstallerSha256: $((Get-FileHash "$distDir\oh-my-posh.exe" -Algorithm SHA256).Hash)
  PortableCommandAlias: oh-my-posh
ManifestType: installer
ManifestVersion: 1.6.0
"@
    
    # 本地化清单
    $localeManifest = @"
PackageIdentifier: $packageId
PackageVersion: $Version
PackageLocale: en-US
Publisher: $publisherName
PublisherUrl: https://gitcode.com/Xuan_er123/oh-my-posh
PublisherSupportUrl: https://gitcode.com/Xuan_er123/oh-my-posh/issues
PackageName: Oh My Posh (Custom Build)
PackageUrl: https://gitcode.com/Xuan_er123/oh-my-posh
License: MIT
LicenseUrl: https://gitcode.com/Xuan_er123/oh-my-posh/blob/main/COPYING
Copyright: Copyright (c) Jan De Dobbeleer
ShortDescription: A blazing fast cross platform/shell prompt with a liquid heart
Description: A blazing fast cross platform/shell prompt with a liquid heart. Custom build from fork.
Moniker: omp-custom
Tags:
- console
- command-line
- shell
- commandline
- prompt
- powershell
- wsl
- developer-tools
- hacktoberfest
- bash
- fish
- zsh
ManifestType: defaultLocale
ManifestVersion: 1.6.0
"@
    
    # 写入文件
    $mainManifest | Out-File "$wingetDir\$packageId.yaml" -Encoding UTF8
    $installerManifest | Out-File "$wingetDir\$packageId.installer.yaml" -Encoding UTF8
    $localeManifest | Out-File "$wingetDir\$packageId.locale.en-US.yaml" -Encoding UTF8
    
    Write-Host "✓ Winget包清单已创建在 $wingetDir\" -ForegroundColor Green
    Write-Host "安装命令: winget install --manifest $wingetDir\" -ForegroundColor Yellow
}

# 步骤5: 本地安装 (可选)
if ($InstallLocal) {
    Write-Host "`n步骤5: 本地安装..." -ForegroundColor Blue
    
    $installDir = "$env:LOCALAPPDATA\Programs\oh-my-posh"
    if (!(Test-Path $installDir)) {
        New-Item -Path $installDir -ItemType Directory -Force | Out-Null
    }
    
    # 复制可执行文件
    Copy-Item "$distDir\oh-my-posh.exe" "$installDir\oh-my-posh.exe" -Force
    
    # 检查PATH中是否已包含安装目录
    $pathList = $env:PATH -split ';'
    if ($installDir -notin $pathList) {
        Write-Host "添加到用户PATH: $installDir" -ForegroundColor Yellow
        $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
        [Environment]::SetEnvironmentVariable("PATH", "$userPath;$installDir", "User")
        Write-Host "请重启PowerShell以使PATH生效" -ForegroundColor Yellow
    }
    
    Write-Host "✓ 已安装到: $installDir" -ForegroundColor Green
    Write-Host "测试安装: oh-my-posh version" -ForegroundColor Yellow
}

Write-Host "`n=== 构建完成 ===" -ForegroundColor Green
Write-Host "可执行文件位置: $distDir\oh-my-posh.exe" -ForegroundColor Cyan

if ($BuildMSI) {
    Write-Host "MSI包位置: packages\msi\out\install-$Architecture.msi" -ForegroundColor Cyan
}

if ($CreateWingetPackage) {
    Write-Host "Winget包位置: $wingetDir\" -ForegroundColor Cyan
}

Write-Host "`n使用说明:" -ForegroundColor Yellow
Write-Host "1. 直接运行: .\$distDir\oh-my-posh.exe" 
Write-Host "2. 使用MSI安装: 双击 packages\msi\out\install-$Architecture.msi"
Write-Host "3. 使用Winget安装: winget install --manifest $wingetDir\"
